package com.auth.project.cn.util;

import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Bean 工具类
 */
@Slf4j
public class BeanUtils {

    private static final Logger logger = LoggerFactory.getLogger(BeanUtils.class);

    /**
     * Bean方法名中属性名开始的下标
     */
    private static final int BEAN_METHOD_PROP_INDEX = 3;

    /**
     * 匹配getter方法的正则表达式
     */
    private static final Pattern GET_PATTERN = Pattern.compile("get(\\p{javaUpperCase}\\w*)");

    /**
     * 匹配setter方法的正则表达式
     */
    private static final Pattern SET_PATTERN = Pattern.compile("set(\\p{javaUpperCase}\\w*)");

    /**
     * Bean属性复制工具方法。
     *
     * @param dest 目标对象
     * @param src  源对象
     */
    public static void copyBeanProp(Object dest, Object src) {
        List<Method> destSetters = getSetterMethods(dest);
        List<Method> srcGetters = getGetterMethods(src);
        try {
            for (Method setter : destSetters) {
                for (Method getter : srcGetters) {
                    if (isMethodPropEquals(setter.getName(), getter.getName())
                            && setter.getParameterTypes()[0].equals(getter.getReturnType())) {
                        setter.invoke(dest, getter.invoke(src));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取对象的setter方法。
     *
     * @param obj 对象
     * @return 对象的setter方法列表
     */
    public static List<Method> getSetterMethods(Object obj) {
        // setter方法列表
        List<Method> setterMethods = new ArrayList<Method>();
        // 获取所有方法
        Method[] methods = obj.getClass().getMethods();
        // 查找setter方法
        for (Method method : methods) {
            Matcher m = SET_PATTERN.matcher(method.getName());
            if (m.matches() && (method.getParameterTypes().length == 1)) {
                setterMethods.add(method);
            }
        }
        // 返回setter方法列表
        return setterMethods;
    }

    /**
     * 获取对象的getter方法。
     *
     * @param obj 对象
     * @return 对象的getter方法列表
     */

    public static List<Method> getGetterMethods(Object obj) {
        // getter方法列表
        List<Method> getterMethods = new ArrayList<Method>();
        // 获取所有方法
        Method[] methods = obj.getClass().getMethods();
        // 查找getter方法
        for (Method method : methods) {
            Matcher m = GET_PATTERN.matcher(method.getName());
            if (m.matches() && (method.getParameterTypes().length == 0)) {
                getterMethods.add(method);
            }
        }
        // 返回getter方法列表
        return getterMethods;
    }

    /**
     * 检查Bean方法名中的属性名是否相等。<br>
     * 如getName()和setName()属性名一样，getName()和setAge()属性名不一样。
     *
     * @param m1 方法名1
     * @param m2 方法名2
     * @return 属性名一样返回true，否则返回false
     */

    public static boolean isMethodPropEquals(String m1, String m2) {
        return m1.substring(BEAN_METHOD_PROP_INDEX).equals(m2.substring(BEAN_METHOD_PROP_INDEX));
    }


    /**
     * 把具有相同字段和类型的bean进行转换
     *
     * @param source
     * @param targetClass
     * @param <T>
     * @return
     */
    public static <T, k> T convert(Object source, Class<T> targetClass) {
        T target = null;

        if (source != null) {
            try {
                target = targetClass.newInstance();
                org.springframework.beans.BeanUtils.copyProperties(source, target);
            } catch (Exception e) {
                logger.error("convert bean is error", e);
            }

        }

        return target;
    }

    /**
     * 把具有相同字段和类型的bean进行转换
     *
     * @param <T>
     * @param source
     * @param targetClass
     * @param <T>
     * @return
     */
    public static <T, k> List<T> convertList(List<k> sourceList, Class<T> targetClass) {
        List<T> convertList = new ArrayList<>();
        for (Object obj : sourceList) {
            convertList.add(convert(obj, targetClass));
        }
        return convertList;
    }

    public static Map<String, String> convert2Map(Object o) {
        if (o == null) {
            return null;
        }

        Map<String, String> map = Maps.newHashMap();
        try {
            map = BeanUtils.convert2Map(o);
        } catch (Exception e) {
            logger.error("bean describe error");
        }

        return map;
    }


    public static Map<String, String> convertMap(Object o) {
        if (o == null) {
            return null;
        }

        Map<String, String> map = Maps.newHashMap();
        try {
            map = BeanUtils.convertMap(o);
        } catch (Exception e) {
            logger.error("bean describe error");
        }

        return map;
    }

    public static <T> T convert(Object source, Class<T> targetClass, String[] ignoreProperties) {
        T target = null;

        if (source != null) {
            try {
                target = targetClass.newInstance();
                org.springframework.beans.BeanUtils.copyProperties(source, target, ignoreProperties);
            } catch (Exception e) {
                logger.error("convert bean is error", e);
            }

        }

        return target;
    }

    public static void setFieldValue(Object object, String fieldName, Object value) {
        Field field = ReflectionUtils.findField(object.getClass(), fieldName);
        if (field == null) {
            throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]");
        }
        ReflectionUtils.makeAccessible(field);
        ReflectionUtils.setField(field, object, value);
    }

    @SuppressWarnings("unchecked")
    public static <T> T getFieldValue(Object object, String fieldName) {
        Field field = ReflectionUtils.findField(object.getClass(), fieldName);
        if (field == null) {
            throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]");
        }
        ReflectionUtils.makeAccessible(field);
        return (T) ReflectionUtils.getField(field, object);
    }

}
